<template>
	<div>
		<el-breadcrumb separator="/">
		  <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
		  <el-breadcrumb-item>商品分类</el-breadcrumb-item>
		</el-breadcrumb>
		<!--商品分类卡片视图-->
		<el-card class="box-card">
		  <el-row>
		  	<el-col>
		  		<el-button type="primary" @click="showAddCateDialog">添加商品分类</el-button>
		  	</el-col>
		  </el-row>
		  <!--树形表格-->
		  <table-tree class="tableTree" :data="categoryList" :columns="columns" :selection-type="false" border index-text="#" show-index :expand-type="false" :show-row-hover="false">
		  	<template slot="isok" slot-scope="scope">
		  		<i class="el-icon-success" v-if="scope.row.cat_deleted === false" style="color: lightgreen;"></i>
		  		<i class="el-icon-error" v-else style="color: red;"></i>
		  	</template>
		  	<!--排序-->
		  	<template slot="order" slot-scope="scope">
		  		<el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
				<el-tag size="mini" v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
				<el-tag size="mini" v-else type="info">三级</el-tag>
		  	</template>
		  	<!--操作-->
		  	<template slot="opt" slot-scope="scope">
		  		<el-button type="primary" icon="el-icon-edit" size="mini" @click="editVisible(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCate(scope.row.cat_id)">删除</el-button>
		  	</template>
		  </table-tree>
		  <!--分页区域-->
		  <el-pagination
	        @size-change="handleSizeChange"
	        @current-change="handleCurrentChange"
	        :current-page="queryInfo.pagenum"
	        :page-sizes="[3, 5, 10, 15]"
	        :page-size="queryInfo.pagesize"
	        layout="total, sizes, prev, pager, next, jumper"
	        :total="total">
	      </el-pagination>
	      <!--添加商品分类对话框-->
          <el-dialog
		    title="添加商品分类"
		    :visible.sync="addCateDialogVisible"
		    width="50%" @close="addCateDialogClosed">
		    <el-form :model="addCateForm" :rules="addCaterules" ref="addCateForm" label-width="100px">
		    	<!--如果级联选择框中 选择一级分类 此时添加的是二级分类，如果选择的是二级分类，那么添加的是三级分类，什么都不选则是一级分类-->
			  <el-form-item label="分类名称" prop="cat_name">
			    <el-input v-model="addCateForm.cat_name" autocomplete="off"></el-input>
			  </el-form-item>
			  <el-form-item label="父级分类">
			     <el-cascader
				    v-model="selectedId"
				    :options="parentCateList"
				    :props="cascaderProps" clearable @change="parentCateChanged" change-on-select>
				 </el-cascader>
			   </el-form-item>
			 </el-form>
		    <span slot="footer" class="dialog-footer">
		      <el-button @click="addCateDialogVisible = false">取 消</el-button>
		      <el-button type="primary" @click="addCate">确 定</el-button>
		    </span>
		  </el-dialog>
		  <!--修改商品分类对话框-->
		   <el-dialog
		    title="修改商品分类"
		    :visible.sync="editCateDialogVisible"
		    width="50%" @close="editCateDialogClosed">
		    <el-form :model="editCateForm" :rules="editCaterules" ref="editCateForm" label-width="100px">
			  <el-form-item label="分类名称" prop="cat_name">
			    <el-input v-model="editCateForm.cat_name" autocomplete="off"></el-input>
			  </el-form-item>
			 </el-form>
		    <span slot="footer" class="dialog-footer">
		      <el-button @click="editCateDialogVisible = false">取 消</el-button>
		      <el-button type="primary" @click="updateCate">确 定</el-button>
		    </span>
		  </el-dialog>
		</el-card>
	</div>
</template>
<script>
export default {
	data () {
		return {
			categoryList: [],
			queryInfo: {
				type: 3,
				pagenum: 1,
				pagesize: 5
			},
			// 添加分类的表单数据对象
			addCateForm: {
                cat_name: '',
                // 父级分类id 级联选择框中选中谁就是当前添加分类表单的父级 默认唯恐
                cat_pid: 0,
                // 分类等级 默认为一级分类
                cat_level: 0

			},
			// 添加分类的表单验证规则
			addCaterules: {
				cat_name: [
                  { required:true, message:"请输入要添加的分类",trigger:"blur" },
				]
			},
			// 修改分类表单的数据对象
			editCateForm: {
				cat_id: 0,
				cat_name: ''
			},
			// 修改分类表单验证规则
			editCaterules: {
				cat_name: [
                  { required:true, message:"请输入要修改的分类",trigger:"blur" },
				]
			},
			// 分页总数默认为零
			total:0,
			// 父级分类数据源对象
            parentCateList: [],
            cascaderProps: {
            	value: 'cat_id',
            	label: 'cat_name',
            	children: 'children',
            	expandTrigger : 'hover'
            },
            // 选中的父级分类的Id数组
            selectedId: [],
			columns: [
              { 
              	label: '分类名称',
              	prop: 'cat_name'
              },
              { 
              	label: '是否有效',
              	type: 'template',
              	template: 'isok'
              },
              {
              	label: '排序',
              	type: 'template',
              	template: 'order'
              },
              {
	            label: '操作',
	            // 表示，将当前列定义为模板列
	            type: 'template',
	            // 表示当前这一列使用模板名称
	            template: 'opt'
	          }
			],
			// 添加商品分类对话框开关控制
			addCateDialogVisible: false,
			// 修改商品分类对话框开关控制
			editCateDialogVisible: false
		}
	},
	created () {
      this.getCategoryList()
      this.getParentCateList()
	},
	methods: {
      async getCategoryList () {
        const { data: res } = await this.$http.get('categories',{ params: this.queryInfo })
        if (res.meta.status !== 200) {
        	return this.$message.error('获取商品列表失败')
        }
        console.log(res)
        this.categoryList = res.data.result
        this.total = res.data.total
      },
      handleSizeChange (pagesize) {
        this.queryInfo.pagesize = pagesize
        this.getCategoryList()
      },
      handleCurrentChange (currentPage) {
      	this.queryInfo.pagenum = currentPage
      	this.getCategoryList()
      },
      showAddCateDialog () {
      	this.addCateDialogVisible = true
      },
      parentCateChanged () {
      	console.log(this.selectedId)
      	//如果要添加1级分类，则父分类Id应该设置为  `0` 
      	if (this.selectedId.length>0) {
      		this.addCateForm.cat_pid = this.selectedId[this.selectedId.length-1]
      		this.addCateForm.cat_level = this.selectedId.length
      		return
      	}else{
      		this.addCateForm.cat_pid = 0
      		this.addCateForm.cat_level = 0
      	}
      },
      // 获取父级商品分类列表
      async getParentCateList () {
        const { data: res } = await this.$http.get('categories',{ params: { type: 2 } })
        if (res.meta.status !== 200) {
        	return this.$message.error('获取父级商品分类列表失败')
        }
        console.log(res.data)
        this.parentCateList = res.data
      },
      // 添加商品分类
      addCate () {
      	this.$refs.addCateForm.validate(async valid => {
      		if (!valid) return
      		const { data: res } = await this.$http.post('categories',this.addCateForm)
      	    if (res.meta.status !== 201) {
      	    	return this.$message.error('添加商品分类失败')
      	    }
      	    this.$message.success('添加分类成功！')
      	    this.getCategoryList()
      	    this.addCateDialogVisible = false
      	})
      },
      addCateDialogClosed () {
      	this.$refs.addCateForm.resetFields()
	    this.selectedId=[]
	    this.addCateForm.cat_pid=0
	    this.addCateForm.cat_level=0
      },
      // 修改商品分类对话框
      editVisible (cateInfo) {
      	this.editCateForm.cat_id = cateInfo.cat_id
      	this.editCateDialogVisible = true
      },
      // 监听修改商品分类对话框关闭时
      editCateDialogClosed () {
      	this.$refs.editCateForm.resetFields()
      },
      // 更新修改后的商品分类
      updateCate () {
      	this.$refs.editCateForm.validate(async valid =>{
      		if (!valid) return
      		const { data: res } = await this.$http.put(`categories/${this.editCateForm.cat_id}`,{ cat_name: this.editCateForm.cat_name})
      	    if (res.meta.status !==200) {
      	    	return this.$message.error('更新商品名称失败')
      	    }
      	    this.$message.success('更新商品分类名称成功')
      	    this.getCategoryList()
      	    this.editCateDialogVisible = false
      	})
      },
      // 按id删除商品分类
      async deleteCate (cateId) {
        console.log(cateId)
      	const confirmResult = await this.$msgbox.confirm('是否确定删除此分类，确定后将永久该分类','提示',{ 
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      	}).catch(val=>val)
      	if (confirmResult !== 'confirm') {
      		return this.$message.info('已取消删除')
      	}
      	const { data: res } = await this.$http.delete(`categories/${cateId}`)
      	if (res.meta.status !== 200) {
      		return this.$message.error('删除分类失败')
      	}
      	this.$message.success('成功删除用户')
      	this.getCategoryList()
      }
	}
}
</script>
<style lang="less" scoped>
	.tableTree{
		margin-top:15px;
	}
</style>